package com.woniuxy.shop.service;

import java.util.List;

import com.woniuxy.shop.dao.DetailOrderDao;
import com.woniuxy.shop.dao.GoodsDao;
import com.woniuxy.shop.dao.OrderDao;
import com.woniuxy.shop.dao.UserDao;
import com.woniuxy.shop.entity.DetailOrder;
import com.woniuxy.shop.entity.Order;
import com.woniuxy.shop.entity.PageBean;
import com.woniuxy.shop.entity.User;
import com.woniuxy.shop.exception.DaoException;
import com.woniuxy.shop.exception.ServiceException;
import com.woniuxy.shop.exception.StockIsEnnoughException;
import com.woniuxy.shop.utils.ShopUtils;

/**
 * @author 作者： version 创建时间： 类说明：
 */
public class OrderService {
	OrderDao od = new OrderDao();
	DetailOrderDao dod = new DetailOrderDao();
	GoodsDao gd = new GoodsDao();
	UserDao ud = new UserDao();

	public void add(Order os, DetailOrder... dor) {
		// 下订单，同时增加订单表和订单明细表
		double totalMoney = os.getMoney();
		int radiusNum = (int) (Math.random() * 9000 + 1000);
		try {
			// 生成订单编号：WN20200323141038XXXX
			String orderNo = "WN" + os.getOrdertime() + radiusNum;

			for (DetailOrder detailOrder : dor) {
				// 判断库存是否足够
				int stock = gd.getStockByID(detailOrder.getGoodsid());
				if (detailOrder.getNums() > stock) {
					throw new StockIsEnnoughException("库存不足,无法满足您的订购数量，当前库存：" + stock);
				}
				// 计算总价格
				totalMoney += gd.getPriceByID(detailOrder.getGoodsid()) * detailOrder.getNums();
				// 更新库存
				gd.updateStock(stock - detailOrder.getNums(), detailOrder.getGoodsid());
			}
			os.setMoney(totalMoney);
			os.setOrderno(orderNo);
			od.add(os);
			int orderId = od.getMaxID();
			// 更新具体订单的订单ID
			for (DetailOrder detailOrder : dor) {
				detailOrder.setOrderid(orderId);
			}
			dod.add(dor);
			// 更新积分
			User u = ud.getUserByID(os.getUserid());
			u.setScore(u.getScore() + (int) totalMoney);
			ud.update(u);

		} catch (DaoException e) {
			throw new ServiceException("sql执行出错", e);
		}
	}

	public PageBean<Order> getPageBean(int page, Order o) {
		int pagesize = 5;
		PageBean<Order> pb = new PageBean<>();
		int totalNum = od.getOrdersAsLimit(o);
		List<Order> orders = od.getOrdersByPage(pagesize, page, o);

		pb.setList(orders);
		pb.setNowNum(orders.size());
		pb.setNowPage(page);
		pb.setPageSize(pagesize);
		pb.setTotalPage(totalNum % pagesize == 0 ? totalNum / pagesize : totalNum / pagesize + 1);
		pb.setTotalNum(totalNum);
		return pb;
	}
	
	/**
	 * 根据id获取订单
	 * @param id
	 * @return
	 */
	public Order getOrder(int id) {
		Order o = null;
		try {
			o = od.getOrder(id);
		} catch (Exception e) {
			throw new ServiceException("sql执行出错", e);
		}
		return o;
	}
	
	/**
	 * 获取最新的订单（id最大）
	 * @return
	 */
	public Order getNewOrder() {
		Order o = null;
		try {
			o = od.getOrder(od.getMaxID());
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错", e);
		}
		return o;
	}
	
	/**
	 * 更新支付时间和支付状态
	 */
	public void updataStatus(int orderid) {
		try {
			od.updateStatus(orderid, "已付款",ShopUtils.getNowTimeWithType());
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错", e);
		}
		
	}
	
	/**
	 * 获取最新的5条未支付订单
	 * @param id
	 * @return
	 */
	public List<Order> getRecentOrders(int userid) {
		List<Order> orders = null;
		try {
			orders = od.getRecentOrders(userid);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错", e);
		}
		return orders;
	}

	/**
	 * 将订单状态更改为已发货
	 * @param orderid
	 */
	public void send(int orderid) {
		try {
			od.send("已发货",orderid);
		} catch (DaoException e) {
			throw new ServiceException("sql执行出错", e);
		}
		
	}
}
